try:
    from typing import Optional, Literal, Union
    from shared_types import DeviceFunctionalConfig
    CONNECTION_STATUS = Literal["connected", "disconnected"]
except ImportError:
    pass
import json
import socket
import time
from bootstrap.fs_services import file_exists


class States:
    def __init__(self) -> None:
        from bootstrap.configs import configs
        from bootstrap.states import bootstrap_states
        self.speed = 0
        self.control_station_ip = ""
        self.udp_socket: "Optional[socket.socket]" = None
        self.configs = configs
        self._functional_configs: "Optional[DeviceFunctionalConfig]" = None
        self.bootstrap_states = bootstrap_states
        self.connection_status: "CONNECTION_STATUS" = "disconnected"
        self.last_keepalive_time = time.time()

    def load_functional_configs(self) -> "Optional[DeviceFunctionalConfig]":
        """
        加载功能配置项
        """
        if file_exists("functional-configs.json"):
            with open("functional-configs.json", "rb") as f:
                return json.load(f)
        else:
            return None

    def save_and_update_functional_configs(self, data: "DeviceFunctionalConfig"):
        """
        保存并更新功能配置项
        """
        self._functional_configs = data
        with open("functional-configs.json", "w") as f:
            json.dump(data, f)

    def get_functional_configs(self) -> "Optional[DeviceFunctionalConfig]":
        """
        获取功能配置项，注意结果有可能为None。
        """
        if self._functional_configs is None:
            self._functional_configs = self.load_functional_configs()
        return self._functional_configs

    def ip(self) -> str:
        from bootstrap.states import bootstrap_states
        return bootstrap_states.ip

    def get_udp_socket(self):
        """
        创建udp socket，接收data数据
        """
        if self.udp_socket is None:
            self.udp_socket = socket.socket(
                socket.AF_INET, socket.SOCK_DGRAM)
        return self.udp_socket


states = States()
